class Solution {
public:
    int totalFruit(vector<int>& fruits) {
        vector<int> s = fruits;
        if(s.size() <= 2) return s.size();
        
        int ret = 0;
        int i = 1;
        vector<int> flag(2,0);
        while(i < s.size() - 1 && s[i] == s[i-1]){
            i++;
        }
        flag[0] = i - 1;
        flag[1] = i;
        int j = i;
        ret = max(ret,i + 1);
        i = 0;
        
        for(;j < s.size();j++){
            if(s[j] == s[flag[0]]){
                flag[0] = j;
            }else if(s[j] == s[flag[1]]){
                flag[1] = j;
            }else{
                i = min(flag[0],flag[1]) + 1;
                flag[0] = max(flag[0],flag[1]);
                flag[1] = j;
            }
            ret = max(ret,j - i + 1);
        }
        return ret;
    }
};
